#import <QuartzCore/QuartzCore.h>
#import "NSString+HTML.h"
#import "MWFeedParser.h"
#import "DetailTableViewController.h"
#import "HJObjManager.h"
#import "HJManagedImageV.h"
#import "AsyncImagesAppDelegate.h"
#import "ColorUtil.h"
#import "MediaBookXMLParser.h"
#import "XMLTable.h"

@implementation XMLTable
@synthesize identifier;
@synthesize suffix;
@synthesize xmlPath;
@synthesize useCharacterPanel;
#pragma mark -
#pragma mark View lifecycle

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    if (self) 
    {  
        self.userInteractionEnabled = TRUE;
        
        // Setup
        formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterShortStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        parsedItems = [[NSMutableArray alloc] init];
        
        table_width = 320;
        table_height = 385;
        table_row_height = 75;

        table_unit_style = 0;
        
        objMan = [[HJObjManager alloc] initWithLoadingBufferSize:10 memCacheSize:25];

        currentTime = 0;
        
        useSpecificUI = FALSE;
        useCharacterPanel = FALSE;
        
        titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 115, 320, 32)];
        titleLabel.font = [UIFont fontWithName:@"STHeitiSC-Medium" size:20];
        //titleLabel.numberOfLines = 0;
        [titleLabel setBackgroundColor:[UIColor clearColor]];
        [titleLabel setTextColor:[ColorUtil stringHexToUIColor:@"0xffffff"]];
        titleLabel.textAlignment = UITextAlignmentCenter;
        [titleLabel setText:@""];

        titleBg = [[UIView alloc] initWithFrame:CGRectMake(0,115,320,30)];
        titleBg.backgroundColor = [UIColor blackColor];
        titleBg.alpha = 0.5f;
    }
    return self;
}

-(void) configTable:(int) inTableWidth
        tableHeight:(int) inTableHeight
         tableWidth:(int) inTableRowHeight
    tableUnitStyle:(int) inTableUnitStyle
{
    table_width = inTableWidth;
    table_height = inTableHeight;
    table_row_height = inTableRowHeight;
    table_unit_style = inTableUnitStyle;
}

-(void) setUpSpecificUI:(UIView *)inView
{
    if (inView != Nil) 
    {
        useSpecificUI = TRUE;
        specificUI = inView;
    }
    
}

-(void) triggerByURL:(NSString*) inURL
       useFeatureImg:(BOOL) ifUseFeatureImg
{
    theTable = [[UITableView alloc] initWithFrame:CGRectMake(0,0, table_width, table_height)];
    theTable.rowHeight = table_row_height;
    theTable.delegate = self;
    theTable.dataSource = self;
    [self addSubview:theTable];
    
    activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicator.frame = CGRectMake(140, 210, 40.0, 40.0);
    [activityIndicator startAnimating];
    [self addSubview:activityIndicator];
    
    useFeaturedImg = ifUseFeatureImg;
    if (useCharacterPanel) 
    {
        lettersPanelComponent = [[LettersPanelComponent alloc] initWithFrame:CGRectMake(0, 0, 320, 140)];
        [lettersPanelComponent initPanel:suffix];
        [self addSubview:lettersPanelComponent];
        theTable.tableHeaderView = lettersPanelComponent;
    }
    else if (useFeaturedImg) 
    {
        featureImgView = [[UIImageLayer alloc] initWithFrame:CGRectMake(0, 0, 300, 145)];
        featureImgView.button_id = 101;
        
        featureImgMsg = [[NSString alloc] initWithFormat:@"feature_img_trigger_%@",suffix];
        loadImgOverMsg =  [[NSString alloc] initWithFormat:@"img_load_over_%@",suffix];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:loadImgOverMsg object:Nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:featureImgMsg object:Nil];
        
        [featureImgView setUpLoadImgOverMsg:suffix];
        [featureImgView initHitMsg:featureImgMsg];
        
        [self addSubview:featureImgView];
        
        [featureImgView addSubview:titleBg];
        [featureImgView addSubview:titleLabel];
        
        theTable.tableHeaderView = featureImgView;
        titleBg.hidden = TRUE;
        titleLabel.hidden = TRUE;
        
        titleBg.hidden = TRUE;
    }
    
    book_load_over_msg = [[NSString alloc] initWithFormat:@"load_book_xml_over_%@",suffix];
        
    xmlPath = inURL;
    
    NSURL *feedURL = [NSURL URLWithString:xmlPath];//
    feedParser = [[MWFeedParser alloc] initWithFeedURL:feedURL];
        
    if (feedAndUnit) 
    {
        feedParser.strType = feedAndUnit;
        feedParser.atomStr = atomUnit;
        feedParser.feedUnitStr = feedUnit;
    }
    
    feedParser.delegate = self;
    feedParser.feedParseType = ParseTypeFull; // Parse feed info and all items
    feedParser.connectionType = ConnectionTypeAsynchronously;
    [feedParser parse];
    
    mediaBookXML = [[MediaBookXMLParser alloc] init];
    mediaBookXML.msgString = [[NSString alloc] initWithString:book_load_over_msg];
    [mediaBookXML startParsing:xmlPath];
}

-(void) setAtomData:(NSString *) inFeedAndUnit
                        atom:(NSString *) inAtomUnit
                         feed:(NSString  *) inFeedUnit
{
    feedAndUnit = [[NSString alloc] initWithString:inFeedAndUnit];
    atomUnit = [[NSString alloc] initWithString:inAtomUnit];
    feedUnit = [[NSString alloc] initWithString:inFeedUnit];
}

-(void) mouseDownProc:(id)sender
{
    ImageUIButton *button = sender;
    if(button.button_id == 11)//refresh
    {
        [self refresh];
    }
}

-(void) notificationSelector:(NSNotification *) notification
{
    NSString *curNotificationName = [notification name];

    if ([curNotificationName isEqualToString:book_load_over_msg])
    {
        if (!useFeaturedImg || useCharacterPanel)
        {
            return;
        }
        
        if (featureImgView != Nil) 
        {
            [featureImgView removeFromSuperview];
            [featureImgView reset];
            [featureImgView release];
        }
        
        featureImgView = [[UIImageLayer alloc] initWithFrame:CGRectMake(0, 0, 300, 145)];
        featureImgView.button_id = 101;
        
        [featureImgView setUpLoadImgOverMsg:suffix];
        [featureImgView initHitMsg:featureImgMsg];
        
        [self addSubview:featureImgView];
        titleBg.hidden = FALSE;
        titleLabel.hidden = FALSE;
        
        theTable.tableHeaderView = featureImgView;
        [featureImgView initImage:mediaBookXML.gDataSet.featureImg useOriginalSize:FALSE ratioMode:2 layerInfo:Nil]; 
        
        [featureImgView addSubview:titleBg];
        [featureImgView addSubview:titleLabel];
        titleBg.hidden = FALSE;
    }
    else if ([curNotificationName isEqualToString:featureImgMsg])
    {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mediaBookXML.gDataSet.featureUrl]];
    }
    else if([curNotificationName isEqualToString:loadImgOverMsg])
    {
        [featureImgView addSubview:titleBg];
        [featureImgView addSubview:titleLabel];
    }
}

#pragma mark -
#pragma mark Parsing

// Reset and reparse
- (void)refresh 
{
    if(CACurrentMediaTime()-currentTime<2)
    {
        return;
    }
	
    currentTime = CACurrentMediaTime();
    [activityIndicator startAnimating];
    
	[parsedItems removeAllObjects];
	
    if (feedParser) 
    {
        [feedParser stopParsing];
        [feedParser release];
    }
    
    NSURL *feedURL = [NSURL URLWithString:xmlPath];//
    feedParser = [[MWFeedParser alloc] initWithFeedURL:feedURL];
    if (feedAndUnit) 
    {
        feedParser.strType = feedAndUnit;
        feedParser.atomStr = atomUnit;
        feedParser.feedUnitStr = feedUnit;
    }
    feedParser.delegate = self;
    feedParser.feedParseType = ParseTypeFull; // Parse feed info and all items
    feedParser.connectionType = ConnectionTypeAsynchronously;
	[feedParser parse];
    
	theTable.userInteractionEnabled = NO;
	theTable.alpha = 0.2;
    
    if (mediaBookXML != Nil) 
    {
        [mediaBookXML reset];
    }
    
    mediaBookXML = [[MediaBookXMLParser alloc] init];
    [mediaBookXML startParsing:xmlPath];
}

#pragma mark -
#pragma mark MWFeedParserDelegate

- (void)feedParserDidStart:(MWFeedParser *)parser {

}

- (void)feedParser:(MWFeedParser *)parser didParseFeedInfo:(MWFeedInfo *)info {

}

- (void)feedParser:(MWFeedParser *)parser didParseFeedItem:(MWFeedItem *)item 
{
	if (item) [parsedItems addObject:item];	
}

- (void)feedParserDidFinish:(MWFeedParser *)parser 
{
    if(activityIndicator)
    {
        [activityIndicator stopAnimating];
    }
    
	theTable.userInteractionEnabled = YES;
	theTable.alpha = 1;
	[theTable reloadData];
}

- (void)feedParser:(MWFeedParser *)parser didFailWithError:(NSError *)error 
{
    [parsedItems removeAllObjects];
	theTable.userInteractionEnabled = YES;
	theTable.alpha = 1;
	[theTable reloadData];
}

#pragma mark -
#pragma mark Table view data source

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [parsedItems count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *CellIdentifier = @"Cell";
    
    HJManagedImageV* myimage;
    UILabel *textLabel;
    UILabel *subLabel;
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        if (table_unit_style == 0) 
        {
            myimage = [[[HJManagedImageV alloc] initWithFrame:CGRectMake(5,5,60,60)] autorelease];
            myimage.tag = 999;
            [cell addSubview:myimage];
        }

        if (table_unit_style == 0) 
        {
            textLabel = [[UILabel alloc] initWithFrame:CGRectMake(85, -10, 215, 50)];
            textLabel.font = [UIFont fontWithName:@"STHeitiSC-Medium" size:13.0];
        }
        else if (table_unit_style == 1 || table_unit_style == 2) 
        {
            textLabel = [[UILabel alloc] initWithFrame:CGRectMake(30,7, 215, 50)];
            textLabel.font = [UIFont fontWithName:@"STHeitiSC-Medium" size:23.0];
        }

        textLabel.tag = 998;
        textLabel.contentMode = UIViewContentModeScaleAspectFill;
        textLabel.lineBreakMode = UILineBreakModeWordWrap;
        textLabel.numberOfLines = 1;
        textLabel.backgroundColor = [UIColor clearColor];
        [cell addSubview:textLabel];
        [textLabel release];
        
        if (table_unit_style == 0) 
        {
            subLabel = [[UILabel alloc] initWithFrame:CGRectMake(85, 20, 200, 50)];
            subLabel.tag = 997;
            subLabel.font = [UIFont fontWithName:@"TrebuchetMS" size:11.0];
            subLabel.contentMode = UIViewContentModeScaleAspectFill;
            subLabel.lineBreakMode = UILineBreakModeWordWrap;
            subLabel.numberOfLines = 3;
            subLabel.backgroundColor = [UIColor clearColor];
            
            [cell addSubview:subLabel];
            [subLabel release];
        }


    } 
    else 
    {
        subLabel  = (UILabel *) [cell viewWithTag:997];
        textLabel = (UILabel *) [cell viewWithTag:998];
        
        // async manage all images for the items of the tableview
        myimage = (HJManagedImageV*)[cell viewWithTag:999];
		[myimage clear];        
        
    }
    
    MWFeedItem *item = [parsedItems objectAtIndex:indexPath.row];
    
	if (item) 
    {
        if(table_unit_style == 0)
        {
            myimage.url = [NSURL URLWithString:item.icon];
            [objMan manage:myimage];
            
            textLabel.text = item.title;        
            subLabel.text = item.content; 
        }
        else if (table_unit_style == 1) 
        {
            textLabel.text = [[NSString alloc] initWithFormat:@"%@(%@)",item.title,item.count];   
        }
        else if (table_unit_style == 2) 
        {
            textLabel.text = [[NSString alloc] initWithFormat:@"%@",item.title];   
        }
        
        if (indexPath.row == 0) 
        {
            [titleLabel setText:item.title];
        }
    }
    
    UIImage *rowBackground;
    UIImage *selectionBackground;
    
    rowBackground = [UIImage imageNamed:@"item_normal.png"];
    selectionBackground = [UIImage imageNamed:@"item_selected.png"];
    UIImageView *rowBackgroundView = [[UIImageView alloc] initWithImage:rowBackground];
    UIImageView *rowBackgroundViewSelected = [[UIImageView alloc] initWithImage:selectionBackground];
    
    cell.backgroundView = rowBackgroundView;
    cell.selectedBackgroundView = rowBackgroundViewSelected;
    
    return cell;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    recent_sel_item_index = indexPath;
    MWFeedItem *tempItemAtom =  (MWFeedItem *)[parsedItems objectAtIndex:indexPath.row];
    identifier = [[NSString alloc] initWithString:tempItemAtom.identifier];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:[[NSString alloc] initWithFormat:@"unit_trigger_%@",suffix] 
                                                                object:tempItemAtom];
}

-(void) releaseSelectedNode
{
    if (theTable == Nil || recent_sel_item_index == Nil) 
    {
        return;
    }
    
    UITableViewCell *cell = [theTable cellForRowAtIndexPath:recent_sel_item_index];
    
    if (cell != Nil) 
    {
        [cell setSelected:FALSE];
    }

}

-(void) configMsg
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) 
                                                 name:book_load_over_msg object:Nil];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
    switch (toInterfaceOrientation){
        case UIInterfaceOrientationPortrait:
        case UIInterfaceOrientationPortraitUpsideDown:
        case UIInterfaceOrientationLandscapeLeft:
        case UIInterfaceOrientationLandscapeRight:
            return YES;
        default:
            return NO;
    }
}

#pragma mark -
#pragma mark Memory management

- (void)dealloc {
	[formatter release];
	[parsedItems release];
	[parsedItems release];
	[feedParser release];
    [super dealloc];
}

@end


